package lime.dql.view;

import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.SWT;

import com.documentum.fc.client.IDfTypedObject;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.IDfAttr;

public class ResultComparator extends ViewerComparator {

	private int propertyIndex;
	private static final int DESCENDING = 1;
	private int direction = DESCENDING;

	public ResultComparator() {
		this.propertyIndex = -1;
		direction = DESCENDING;
	}

	public int getDirection() {
		return direction == 1 ? SWT.DOWN : SWT.UP;
	}

	public void setColumn(int column) {
		if (column == this.propertyIndex) {
			// Same column as last sort; toggle the direction
			direction = 1 - direction;
		} else {
			// New column; do an ascending sort
			this.propertyIndex = column;
			direction = DESCENDING;
		}
	}

	@Override
	public int compare(Viewer viewer, Object e1, Object e2) {
		
		int rc = 0;
		
		if (propertyIndex == -1) {
			return rc;
		}
			
		
		IDfTypedObject p1 = (IDfTypedObject) e1;
		IDfTypedObject p2 = (IDfTypedObject) e2;
		
		try {
			
			IDfAttr att = p1.getAttr(propertyIndex);
			String attName = att.getName();
			
			rc = p1.getString(attName).compareTo(p2.getString(attName));
			
		} catch (DfException e) {
			e.printStackTrace();
		}
		
		// If descending order, flip the direction
		if (direction == DESCENDING) {
			rc = -rc;
		}
		return rc;
	}

}
